<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

  <img src="./assets/images/sample.jpg" alt="" style="display: none;">

  <canvas width="400" height="400" style="background-color: beige;"></canvas>

  <script>
    // 1. 找到canvas的DOM对象
    let canvas = document.querySelector('canvas');
    // 2. 生成绘图环境
    let ctx = canvas.getContext('2d');

    // 画圆、四边形、三角形、线段、多边形.....
    ctx.arc(200, 200, 100, 0, 2 * Math.PI);
    ctx.stroke();

    // 剪裁图片
    // 先找到图片，等图片加载完毕后，才能剪裁
    let img = document.querySelector('img');
    img.onload = function () {
      ctx.drawImage(img, 300, 300, 300, 300, 0, 0, 400, 400);
      let base64 = canvas.toDataURL('image/jpeg', 0.3);
      console.log(base64);
    }
  </script>

</body>

</html>